import 'dart:io';

import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/common/play_audio.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/xspace/detail/xcomment_voice.dart';
import 'package:find_friend/pages/xspace/post/xpost_editimg_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_pickers/Media.dart';
import 'package:image_pickers/image_pickers.dart';

class XPostPage extends StatefulWidget {
  @override
  _XPostPageState createState() => _XPostPageState();
}

class _XPostPageState extends State<XPostPage> {

  FocusNode focusNode = FocusNode();
  TextEditingController controller = TextEditingController();
  List<File> list = [];
  int imgCount = 1;
  bool isdele = false;
  String deleteContext = "拖动到此处删除";
  String voicepath;
  int voiceduration = 0; // 改变的duration
  int currVoiceDuration = 0; // 不变的duration
  bool isplay = false;
  double _postOpacity = 0.5; // 

  // 发布条件
  int notMySchool; // 本校不可见
  int isShowMain;   // 不显示再我的主页
  int lovers;       // 情侣身份发布

  // 上传图片对应的语音
  List<Map> imgVoices = [];

  //从照片选择
  void _album() async {
    List<Media> _listImagePaths = await ImagePickers.pickerPaths(
      galleryMode: GalleryMode.image,
      selectCount: 4 - list.length,
      showCamera: false,
      // compressSize: 500,
      // cropConfig :CropConfig(enableCrop: true,height: 1,width: 1),
    );
    List<File> _temp = [];
    _listImagePaths.forEach((e) { _temp.add(File(e.path)); });
    _changePostOpacity();
    setState(() {
      list.addAll(_temp);
      imgCount = list.length == 4 ? 4 : list.length + 1;
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  _requestPostArtcle() {
    AlertTool.showLoadingDialog(context);
    Networktool.postArticle(API.article, (data){
      if(data != null) {
        AlertTool.showToast("发布成功");
        Navigator.of(context).pop(data["data"]);
      }
    }
    ,images: list.length == 0 ? null : list
    ,recordPath: voicepath
    ,params: controller.text == "" ? null : {"content": controller.text}
    ,voices: imgVoices
    ,lovers: lovers
    ,main: isShowMain
    ,schoolType: notMySchool
    ,fail: (msg) => AlertTool.showToast(msg)
    ,finaly: () => Navigator.of(context).pop()
    );
  }

  void _changePostOpacity() {
    if(controller.text == "" && list.length == 0 && voicepath == null) {
      setState(() {
        _postOpacity = 0.5;
      });
    } else {
      setState(() {
        _postOpacity = 1.0;
      });
    }
  }

  _postAction() async {
    if(controller.text == "" && list.length == 0 && voicepath == null) {
      return;
    }
    _requestPostArtcle();
  }

  void _deleimageIdx(int idx) async {
    list.removeAt(idx);
    setState(() {
      imgCount = list.length == 4 ? 4 : list.length + 1;
      if(idx < imgVoices.length){
        final temp = imgVoices.removeAt(idx); // 删除语音同时删除对应的文件
        File(temp["path"]).deleteSync();
      }
    });
    _changePostOpacity();
  }

  _play() {
    MyNetWorkPlayer.instance.play(sender: voicepath, islocal: true, audioduration: currVoiceDuration, onPlayDuration: (second){
      if(mounted) {
        setState(() {
          voiceduration = currVoiceDuration - second == -1 ? currVoiceDuration : currVoiceDuration - second;
          if(currVoiceDuration - second == -1) isplay = false;
        });
      }
    });
  }

  void _showRecord(BuildContext context) {
    AlertTool.showVoiceBottomDialog(context, onFinish: (path, duration){
      setState(() {
        voicepath = path;
        voiceduration = duration;
        currVoiceDuration = duration;
      });
      _changePostOpacity();
    });
  }

  @override
  Widget build(BuildContext context) {

    final size = MediaQuery.of(context).size;
    final padding = MediaQuery.of(context).padding;
    final width = (size.width - 40 - 5 * 3) / 4.0;
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text("发贴"),
        centerTitle: true,
        actions: [
          Opacity(
            opacity: _postOpacity,
            child: FlatButton(
              onPressed: _postAction,
              highlightColor: Colors.transparent,
              splashColor: Colors.transparent,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 3),
                decoration: BoxDecoration(
                  color: APP_main_color,
                  borderRadius: BorderRadius.circular(20)
                ),
                child: Text("发布", style: instanceTextStyle(14, Colors.white),)
              ),
            ),
          )
        ],
        leading: IconButton(
          onPressed: (){
            Navigator.of(context).pop();
          },
          icon: Image.asset("assets/fanhui.png"),
        ),
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: (){
          focusNode.unfocus();
        },
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    height: 98.5.h,
                    child: TextField(
                      autocorrect: false,
                      focusNode: focusNode,
                      controller: controller,
                      maxLines: null,
                      decoration: InputDecoration(
                        hintStyle: instanceTextStyle(14, APP_font_deep_grey),
                        labelStyle: instanceTextStyle(14, APP_font_black),
                        hintText: "分享你的新鲜事叭～",
                        counterText: "",
                        contentPadding: const EdgeInsets.only(left: 11.5),
                        border: InputBorder.none,
                      ),
                      onTap: (){
                      },
                      onChanged: (val) => _changePostOpacity(),
                      onEditingComplete: (){
                      },
                    ),
                  ),

                  Container(
                    height: width,
                    margin: const EdgeInsets.only(top: 5),
                    child: Wrap(
                      spacing: 5,
                      children: List.generate(imgCount, (index) { 
                          if(list.length != 4 && index == list.length) {
                            return GestureDetector(
                              onTap: _album,
                              child: Container(
                                      height: width,
                                      width: width,
                                      decoration: BoxDecoration(
                                        color: Colors.white,
                                        border: Border.all(color: APP_divider_color, width: 0.5),
                                        borderRadius: BorderRadius.circular(5)
                                      ),
                                      child: Icon(Icons.add,size: 50, color: APP_divider_color,)
                                    ),
                            );
                          } else {
                            // 语音+图片
                            return XPostDraggImgWidget(
                              list: list,
                              width: width, 
                              index: index,
                              imgVoice: imgVoices,
                              isshowImgVoiceIcon: index < imgVoices.length ? imgVoices[index]?.isNotEmpty : false,
                              onBegin: (){  // 拖动开始显示删除按钮
                                setState(() {
                                  isdele = !isdele;
                                });
                              },
                              onEnd: (){  // 拖动结束，隐藏删除按钮
                                setState(() {
                                  isdele = !isdele;
                                  deleteContext = "拖动到此处删除";
                                });
                              },
                              onDelete: _deleimageIdx, // 编辑完成删除对应图片、语音
                              onEditfinish: (List<Map> voiceSource){ // 编辑完成获取语音数据
                                setState(() {
                                  imgVoices = voiceSource;
                                });
                              },
                            );
                          }
                        }
                      ).toList(),
                    )
                  ),
                  // 语音试听
                  Opacity(
                    opacity: voicepath == null ? 0.3 : 1.0,
                    child: GestureDetector(
                      onTap: (){
                        if(voicepath == null) {
                          _showRecord(context);
                          return;
                        }
                        setState(() {
                          isplay = !isplay;
                        });
                        _play();
                      },
                      child: FlrTestPlatWidget(
                        width: 120,
                        margin: const EdgeInsets.symmetric(vertical: 15),
                        padding: EdgeInsets.symmetric(vertical: 3, horizontal: 5),
                        isplay: isplay, duration: voiceduration
                      ),
                    ),
                  ),

                  Divider(color: APP_divider_color, height: 0.5,),
                  GestureDetector(
                    onTap: (){
                      _showRecord(context);
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 11),
                      child: Row(
                        children: [
                          Image.asset("assets/luyin11.png"),
                          SizedBox(width: 10,),
                          Expanded(child: Text("语音录入", style: instanceTextStyle(14, APP_font_black),)),
                          Image.asset("assets/yuyin55.png")
                        ],
                      ),
                    ),
                  ),
                  Divider(color: APP_divider_color, height: 0.5,),
                  XPostSelectWidget(title: "本校不可见", onTap: (select) => select ? notMySchool = 1 : notMySchool = null),
                  Divider(color: APP_divider_color, height: 0.5,),
                  XPostSelectWidget(title: "情侣身份发布", onTap: (select) => select ? lovers = 1 : lovers = null),
                  Divider(color: APP_divider_color, height: 0.5,),
                  XPostSelectWidget(title: "不显示在我的主页", onTap: (select) => select ? isShowMain = 1 : isShowMain = null),
                  Divider(color: APP_divider_color, height: 0.5,),
                  
                ],
              ),
            ),
            Spacer(),
            Offstage(
              offstage: !isdele,
              child: DragTarget<int>(
                onWillAccept: (data){
                  setState(() {
                    deleteContext = "松手即可删除";
                  });
                  return true;
                },
                onAccept: _deleimageIdx, // 拖动删除对应语音
                builder: (context, accepted, rejected){
                  return Container(
                    width: size.width,
                    height: (40 + padding.bottom).h,
                    color: Colors.redAccent,
                    alignment: Alignment.center,
                    padding: EdgeInsets.only(bottom: padding.bottom / 2),
                    child: Text(deleteContext, style: instanceTextStyle(14, Colors.white),),
                  );
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}

class XPostDraggImgWidget extends StatefulWidget {

  final double width;
  final int index;
  final Function onBegin; // 拖动开始
  final Function onEnd;   //拖动结束
  final List<File> list;
  final Function(int index) onDelete;       // 删除图片
  final Function(List<Map> val) onEditfinish; // 编辑图片，给图片添加语音
  final List<Map> imgVoice; // 图片对应的语音
  final bool isshowImgVoiceIcon;

  const XPostDraggImgWidget({
    Key key, 
    this.width, 
    this.index, 
    this.onBegin, 
    this.onEnd,
    this.list,
    this.onDelete,
    this.onEditfinish,
    this.imgVoice,
    this.isshowImgVoiceIcon = false
  }) : super(key: key);

  @override
  _XPostDraggImgWidgetState createState() => _XPostDraggImgWidgetState();
}

class _XPostDraggImgWidgetState extends State<XPostDraggImgWidget> {

  bool isbegindrag = false;
  @override
  void initState() {
    super.initState();
    
  }

  Widget _create({double opcity = 1, double size = 1}) {
    return Stack(
      children: [
          Opacity(
            opacity: opcity,
            child: PhysicalModel(
            color: Colors.white,
            clipBehavior: Clip.antiAlias,
            borderRadius: BorderRadius.circular(5),
            child: Hero(
              tag: "xpost" + widget.index.toString(),
              child: Image.file(widget.list[widget.index], fit: BoxFit.cover,width: widget.width * size, height: widget.width * size,)
            )
        ),
          ),
        Positioned(
          left: 5,
          bottom: 5,
          child: Offstage(
            offstage: !widget.isshowImgVoiceIcon,
            child: Image.asset("assets/shengyin3.png",)
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Draggable(
      feedback: _create(opcity: 0.7, size: 1.2),
      child: Offstage(
        offstage: isbegindrag,
        child: GestureDetector(
          onTap: () {
           push(context, XPostEditImgPage(
               list: widget.list, 
               onDelete: widget.onDelete,
               onEditFinish: widget.onEditfinish,
               imgVoice: widget.imgVoice,
               heroTag: "xpost" + widget.index.toString(),
             ));
          },
          child: _create()
        ),
      ),
      data: widget.index,
      onDragEnd: (detail){
        setState(() {
          isbegindrag = !isbegindrag;
        });
        widget.onEnd();
      },
      onDragStarted: (){
        setState(() {
          isbegindrag = !isbegindrag;
        });
        widget.onBegin();
      },
    );
  }
}

class XPostSelectWidget extends StatefulWidget {

  final String title;
  final Function(bool isselect) onTap;
  const XPostSelectWidget({Key key, this.title, this.onTap}) : super(key: key);
  @override
  _XPostSelectWidgetState createState() => _XPostSelectWidgetState();
}

class _XPostSelectWidgetState extends State<XPostSelectWidget> {

  bool isselect = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        setState(() {
          isselect = !isselect;
        });
        if(widget.onTap != null) widget.onTap(isselect);
      },
      child: Container(
              padding: EdgeInsets.symmetric(vertical: 11.h),
              child: Row(
                children: [
                  SelectIconWidget(isselect: isselect, width: 15,),
                  SizedBox(width: 10,),
                  Expanded(child: Text(widget.title, style: instanceTextStyle(14, APP_font_black),)),
                ],
              ),
            ),
    );
  }
}